/*
 * Copyright 2013 Solace Systems, Inc.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.solacesystems.tools.ant;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.tools.ant.DirectoryScanner;

/**
 * Simple command line interface to the link checker
 * @author swilson
 *
 */
public class CommandLine {
	private static boolean _dirty = false;
	
	/**
	 * Run the link checker from the command line.
	 * @param args List of URIs to scan for missing links
	 */
	public static void main(String[] args) {
		
		// Display the command line usage
		if (args.length < 1) {
			printUsage(args);
			return;
		}
		
		// Build the crawler
		final Crawler c = new Crawler(new Crawler.EventHandler() {
			@Override
			public void error(Location location, Exception ex) {
				if (ex instanceof URISyntaxException) {
					log("Malformed URI", location, null);
				} else {
					log("Exception", location, ex);
				}
			}
			
			@Override
			public void missing(URI file, Location[] locations) {
				logMissing(file, locations);
			}
		});
		
		c.setFollowLinks(true);
		c.setStripQueryAndFragment(true);
		
		File basedir = new File(".");
		try {
			basedir = basedir.getCanonicalFile();
		} catch (IOException e) {
			System.err.println("Unable to open working directory");
			System.exit(1);
		}
		
		/*
		 * The following block is a hacky way to get DirectoryScanner to support
		 * absolute paths on windows.
		 */
		for (int ii = 0; ii < args.length; ii++) {
			File orig = new File(args[ii]);
			File absolute = orig.getAbsoluteFile();
			
			// Find the root directory (aka the drive on Windows)
			File root = absolute;
			while (root.getParentFile() != null) {
				root = root.getParentFile();
			}
		
			// Convert the absolute path to one relative to the root directory
			orig = new File(root.toURI().relativize(absolute.toURI()).getPath());
			
			DirectoryScanner scanner = new DirectoryScanner();
			scanner.setBasedir(root);
			scanner.setIncludes(new String[] {orig.toString()});
			scanner.scan();
			for (String path : scanner.getIncludedFiles()) {
				File file = new File(root, path);
				c.addTarget(file.toURI());
			}
		}
		
		
		c.crawl();
		
		System.exit(_dirty ? 1 : 0);
	}
	
	private static void log(String msg, Location location, Exception e) {
		System.err.println("* " + msg);
		if (location != null) {
			System.err.println("\tIn " + location.toString());
		}
		if (e != null) {
			e.printStackTrace();
		}
	}
	
	private static void logMissing(URI uri, Location[] references) {
		_dirty = true;
		System.err.println("* File not found: " + uri);
		for (Location ref : references) {
			System.err.println("\tReferenced from " + ref.toString());
		}
	}
	
	private static void printUsage(String[] args) {
		System.out.println("Usage:");
		System.out.println();
		System.out.println("linkcheck <path1> [<path2>|...]");
	}
	
}
